<script type="text/ecmascript-6">
    import b from '../bus'
    import qr from 'qrcode'

    export default {
        data () {
            return {
                loading: false,
                currentPage: 1,
                total: 100,
                pageSize: 50,
                searchField: '',
                LIST: [],
                partnerList: [],
                photographerList: [],
                formVisible: false,
                submiting: false,
                pointActID: -1,
                uploadDialogVisible: false,
                uploadDialogBtnTxt: '关闭对话框',
                uploadDisabled: false,
                form: {
                    code: '',
                    partner: '',
                    name: '',
                    time: '',
                    photographer: [],
                },
                rules: {
                    code: [
                        {required: true, message: '请填写摄影师对应邀请码', trigger: 'blur'},
                    ],
                    partner: [
                        {required: true, message: '请选择合作方', trigger: 'change'},
                    ],
                    name: [
                        {required: true, message: '请填写活动名称', trigger: 'blur'},
                    ],
                    time: [
                        {required: true, message: '请选择活动时间', trigger: 'change'},
                    ],
                    photographer: [
                        {required: true, message: '请选择摄影师', trigger: 'blur'},
                    ],
                },
                statusMap: ['', 'active', 'active', 'end'],
                statusTxtMap: ['', '直播中', '直播中', '已结束'],
            }
        },
        computed: {
            headers () {
                return {
                    'X-CSRFToken': this.user.token
                }
            },
            user () {
                return this.$store.state.user
            },
            filter () {
                return this.$route.params.filter
            },
            formTitle () {
                return '添加活动'
            },
            isAdmin () {
                return this.user.role === 4
            },
            isHand () {
                return this.user.role === 3
            },
            uploadAPI () {
                return `${apiHost}/activities/${this.pointActID}/banners/`
            }
        },
        async mounted () {
            this.getList()
            if (this.isAdmin) {
                this.getPartnerList()
                this.getPhotographerList()
            }
            document.addEventListener('keyup', (e) => {
                if (e.keyCode == '13') {
                    this.getList()
                }
            }, false)
        },
        methods: {
            async getList (currentPage = 1) {
                let postData = {
                    page: currentPage,
                    status__in: this.filter
                }
                if (this.searchField) {
                    postData.name__contains = this.searchField
                }
                this.loading = true
                let res = await this.api.getActivityList(postData)
                if (res.success) {
                    this.LIST = res.data.results.map(e => {
                        let ele = e
                        ele.statusClass = this.statusMap[e.status]
                        ele.statusTxt = this.statusTxtMap[e.status]
                        ele.isAdmin = this.isAdmin
                        return ele
                    })
                    this.total = res.data.count
                }
                this.loading = false
                this.LIST.forEach((e, i) => {
                    this.getBanner(e.id, i)
                    qr.toDataURL(`${window.location.hostname}:6060/${e.id}`, { errorCorrectionLevel: 'H'}, (error, url) => {
                        if (error) console.error(error)
                        this.LIST[i].qr = url
                        console.log('success!');
                    })
                })
            },
            async getBanner (actId, idx) {
                let res = await this.api.getBanners(actId)
                if (res.success) {
                    this.LIST[idx].banners = res.data.results
                    let tem = JSON.parse(JSON.stringify(this.LIST[idx]))
                    tem.hasBanner = res.data.results.length > 0
                    this.LIST.splice(idx, 1, tem)
                }
            },
            lookDetail (id) {
                b.$emit('changePage', 'activityDetail', id)
            },
            async endActivity (act) {
                let self = this

                this.$Modal.confirm({
                    title: '确认结束',
                    content: `<p>确认结束【${act.name}】该活动吗？</p>`,
                    loading: true,
                    onOk: async () => {
                        let res = await self.api.endActivity(act.id, act)
                        if (res.success) {
                            self.$Modal.remove();
                            this.getList()
                            this.$Message.success('结束活动成功！')
                        } else {
                            self.$Modal.remove();
                        }

                    }
                });
            },
            async sureToEnd (id) {
                let res = await this.api.endActivity(id)
                if (res.success) {
                }
            },
            handleFilterChange () {
                this.getList()
            },
            showAddForm () {
                this.formVisible = true
            },
            hideAddForm () {
                this.$refs.form.resetFields()
                this.formVisible = false
            },
            async getPartnerList () {
                let res = await this.api.getPartnerList({page: 1, page_size: 1000})
                if (res.success) {
                    this.partnerList = res.data.results.map(e => {
                        return {
                            value: e.id,
                            label: e.name
                        }
                    })
                }
            },
            async getPhotographerList () {
                let res = await this.api.getPhotographerList({page: 1, page_size: 1000})
                if (res.success) {
                    this.photographerList = res.data.results.map(e => {
                        return {
                            value: e.id,
                            label: e.name
                        }
                    })
                }
            },
            dateChange (val) {
                this.form.time = val
            },
            submit () {
                this.$refs.form.validate(async (valid) => {
                    if (valid) {
                        if (this.isAdmin) {
                            let postData = {
                                end_at: this.form.time.split(' - ')[0],
                                create_at: this.form.time.split(' - ')[0],
                                start_at: '2017-04-10 00:00',
                                photographers: this.form.photographer.map(e => {
                                    return {photographer: e}
                                }),
                                name: this.form.name,
                                partner: this.form.partner
                            }
                            let res = await this.api.createActivity(postData)
                            if (res.success) {
                                this.hideAddForm()
                                this.$Message.success('创建活动成功！')
                                this.getList()
                            }
                        } else {
                            let cameraId
                            let activity
                            let res = await this.api.getCameraID(this.form.code)
                            if (res.success) {
                                cameraId = res.data.id
                                activity = res.data.activity
                                let res2 = await this.api.joinActivity(activity, cameraId)
                                if (res2.success) {
                                    this.hideAddForm()
                                    this.getList()
                                }
                            }

                        }
                    }
                })
            },
            changePage (pageIdx) {
                this.getList(pageIdx)
            },
            showUpload (actId) {
                this.pointActID = actId
                this.uploadDialogVisible = true
            },
            hideUploadDialog () {
                this.pointActID = -1
                this.uploadDialogVisible = false
            },
            delBanner (actId, bannerId) {
                let self = this

                this.$Modal.confirm({
                    title: '确认删除',
                    content: `<p>确认删除该banner吗？</p>`,
                    loading: true,
                    onOk: async () => {
                        let res = await self.api.delBanner(actId, bannerId)
                        if (res.success) {
                            self.$Modal.remove();
                            this.$Message.success('删除成功！')
                            let idx = this.LIST.findIndex(e => e.id === actId)
                            this.getBanner(actId, idx)
                        } else {
                            self.$Modal.remove();
                        }

                    }
                });

            },
            uploading () {
                this.uploadDisabled = true
                this.uploadDialogBtnTxt = '上传中，请勿关闭'
            },
            uploadFinish () {
                let idx = this.LIST.findIndex(e => e.id === this.pointActID)
                this.getBanner(this.pointActID, idx)
                this.uploadDisabled = false
                this.uploadDialogBtnTxt = '关闭对话框'
            },
            uploadFailed () {
                this.uploadDisabled = false
                this.uploadDialogBtnTxt = '关闭对话框'
            },
            downloadQR (data, name) {
                let tag = document.createElement('a')
                tag.href = data
                tag.setAttribute('download', '-' + name + '二维码')
                tag.click()
            }
        },
        watch: {
            '$route.params': 'handleFilterChange',
            isAdmin (val) {
                if (val) {
                    this.getPartnerList()
                    this.getPhotographerList()
                    this.getList()
                }
            }
        }
    };
</script>

<template>
  <div layout="column top-center" class="statistic">
    <div class="statistic__search">
      <Input v-model="searchField" size="large" placeholder="请输入关键字">
      <Button @click="getList(1)" slot="append" icon="ios-search"></Button>
      </Input>
    </div>
    <!-- 活动列表-->
    <div v-if="LIST.length !== 0" class="statistic__content cf">
      <Card v-for="(act, index) in LIST" :key="index" class="statistic__item">
        <div slot="title">
          <span class="statistic__status-dot" :class="act.statusClass"></span>
          <span class="statistic__status-text">{{act.statusTxt}}</span>
        </div>
        <span slot="extra" @click="endActivity(act)" v-if="isAdmin && act.status !== 3">
                    <Icon type="power"></Icon>
                    结束活动
                </span>
        <div class="statistic__body" @click="lookDetail(act.id)">
          <h4 class="statistic__title">{{act.name}}</h4>
          <div class="statistic__banner" v-if="isAdmin">
            <div v-if="!act.hasBanner" class="statistic__no-banner" @click.stop="showUpload(act.id)">
              点击添加banner



            </div>
            <div v-if="act.hasBanner" class="statistic__banner-inner" layout="row center-spread"
                 @click.stop="showUpload(act.id)">
              <img v-for="img in act.banners" @click.stop="delBanner(act.id, img.id)" class="statistic__banner-img"
                   :src="img.file + '?imageView2/2/w/6000/h/120/q/75'">
            </div>
          </div>
          <p class="statistic__no">
            <Icon type="flag" style="margin-right: 6px;"/>
            {{act.search_no}}




          </p>
          <h4 class="statistic__time">
            <Icon type="ios-clock-outline"/>
            {{act.start_at}}




          </h4>
          <div class="statistic__share" @click.stop="downloadQR(act.qr, act.name)">分享活动
            <img :src="act.qr" class="statistic__qr" :class="'qr' + index" />
          </div>
        </div>
      </Card>
    </div>
    <div v-else class="hx__empty">
      <Icon type="images"></Icon>
      暂无活动




    </div>
    <!-- 分页-->
    <Page :page-size="pageSize" :current="currentPage" :total="total" class-name="statistic__pager"
          @on-change="changePage"></Page>
    <!-- SPIN-->
    <Spin size="large" fix v-if="loading"></Spin>

    <!-- 添加活动按钮-->
    <div class="statistic__add" layout="row center-left" @click="showAddForm" v-if="isAdmin || isHand">
      <Icon type="plus" style="margin-right: 5px;"></Icon>
      添加活动




    </div>
    <!-- 添加活动表单-->
    <Modal
            v-model="formVisible"
            :title="formTitle"
            :mask-closable="false"
    >

      <Form class="statistic__form" ref="form" :model="form" :rules="rules" :label-width="100">

        <div v-if="isAdmin">
          <Form-item label="合作方">
            <Input v-model="form.partner" v-show="false"/>
            <Select v-model="form.partner" placeholder="请选择合作方">
              <Option v-for="item in partnerList" :value="item.value" :key="item.value">{{ item.label }}</Option>
            </Select>
          </Form-item>
          <Form-item prop="name" label="活动名称">
            <Input v-model="form.name" placeholder="请输入活动名称"/>
          </Form-item>
          <Form-item prop="time" label="活动时间">
            <Date-picker type="datetimerange" format="yyyy-MM-dd HH:mm" placeholder="选择活动起止时间"
                         @on-change="dateChange"></Date-picker>
            <Input v-model="form.time" v-show="false"/>
          </Form-item>
          <Form-item label="指派摄影师">
            <Select v-model="form.photographer" placeholder="请选择摄影师(可多选)" filterable multiple>
              <Option v-for="item in photographerList" :value="item.value" :key="item.value">{{ item.label }}</Option>
            </Select>
          </Form-item>
        </div>
        <Form-item v-else prop="code" label="邀请码">
          <Input v-model="form.code" placeholder="请输入邀请码"/>
        </Form-item>
      </Form>
      <div slot="footer">
        <Button type="text" @click="hideAddForm">取消</Button>
        <Button v-if="isAdmin" type="primary" size="large" :loading="submiting" @click="submit">创建活动</Button>
        <Button v-else type="primary" size="large" :loading="submiting" @click="submit">确认</Button>
      </div>
    </Modal>

    <Modal
            v-model="uploadDialogVisible"
            title="上传照片"
            @on-ok="getList"
    >
      <Upload
              multiple
              type="drag"
              :action="uploadAPI"
              :with-credentials="true"
              :headers="headers"
              :on-progress="uploading"
              :on-success="uploadFinish"
              :on-error="uploadFailed"
              accept="image/jpg,image/jpeg"
      >
        <div style="padding: 20px 0">
          <Icon type="ios-cloud-upload" size="52" style="color: #3399ff"></Icon>
          <p>点击或将文件拖拽到这里上传Banner（可批量）</p>
        </div>
      </Upload>
      <div slot="footer">
        <Button :disabled="uploadDisabled" :loading="uploadDisabled" type="primary" size="large" long
                @click="hideUploadDialog">{{uploadDialogBtnTxt}}








        </Button>
      </div>
    </Modal>
  </div>
</template>